package com.chinasoft.ssm.service.impl;

import com.chinasoft.ssm.mapper.AccountMapper;
import com.chinasoft.ssm.mapper.TblAccountMapper;
import com.chinasoft.ssm.pojo.Account;
import com.chinasoft.ssm.pojo.TblAccount;
import com.chinasoft.ssm.pojo.TblAccountExample;
import com.chinasoft.ssm.service.AccountService;
import com.chinasoft.ssm.service.LogService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.io.FileNotFoundException;
import java.util.List;

@Service
public class AccountServiceImpl implements AccountService {

    // @Autowired
    //private AccountMapper accountDao;
    @Autowired
    TblAccountMapper accountDao;
    @Autowired
    LogService logService;

    public void save(TblAccount account) {
        accountDao.insert(account);
    }

    public void update(TblAccount account) {
        accountDao.updateByPrimaryKey(account);
    }

    public void delete(Integer id) {

        accountDao.deleteByPrimaryKey(id);
    }


    public TblAccount findById(Integer id) {
        return accountDao.selectByPrimaryKey(id);
    }

    public TblAccount findByName(String name) {
        TblAccountExample example = new TblAccountExample();
        TblAccountExample.Criteria crit = example.createCriteria();
        crit.andNameEqualTo(name);
        List<TblAccount> accList = accountDao.selectByExample(example);
        if (accList.size() >= 1) {
            return accList.get(0);
        } else {
            return null;
        }
    }

    @Override
    public Boolean transfer(String from, String to, Double money) throws FileNotFoundException {
        boolean flag = true;
        try {
            // 查询 from 用户
            TblAccount fromAcc = this.findByName(from);
            // 查询 to 用户
            TblAccount toAcc = this.findByName(to);
            // 修改 javaBean 进行转账
            // 修改to 用户
            toAcc.setMoney(toAcc.getMoney() + money);
            accountDao.updateByPrimaryKey(toAcc);
            // 修改from 用户
            if (fromAcc.getMoney() >= money) {
                fromAcc.setMoney(fromAcc.getMoney() - money);
                accountDao.updateByPrimaryKey(fromAcc);
            } else {
                System.out.println("转账失败，from用户余额不足");
                flag = false;
                // 抛出异常
                throw new RuntimeException("转账失败，from用户余额不足");
//            throw new FileNotFoundException("teacher created");
//            return false;
            }
        } finally {
            // 不管是否有异常
            // 日志记录
            logService.save(from, to, money, flag);
        }

        return true;
    }

    public List<TblAccount> findAll() {
        return null;
    }
}